﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BZOrderPrint
{
    public partial class FrmSetDefaultPrinter : Form
    {
        [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern long SetDefaultPrinter(string pszPrinter);

        public string SelPrintName = string.Empty;

        public FrmSetDefaultPrinter()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SelPrintName = string.Empty;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lbPrintList.SelectedItem != null)
            {
                SelPrintName = lbPrintList.SelectedItem.ToString();
                SetDefaultPrinter(lbPrintList.SelectedItem.ToString());
                MessageBox.Show("设置成功！");
            }
            else
            {
                MessageBox.Show("请选择打印产品说明的打印机！");
            }
        }

        private void lbPrintList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (var lvi in lbPrintList.SelectedItems)
                {
                    labDefault.Text = lvi.ToString();
                }
            }
            catch (Exception) { }
        }

        private void FrmSetDefaultPrinter_Load(object sender, EventArgs e)
        {
            labDefault.Text = "";
            PrintDocument print = new PrintDocument();
            string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
            labDefault.Text = sDefault;
            List<string> list = new List<string>();
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                lbPrintList.Items.Add(sPrint);
            }
            //选中默认打印机
            for (int i = 0; i < lbPrintList.Items.Count; i++)
            {
                string name = lbPrintList.Items[i].ToString();
                if (name == sDefault)
                {
                    lbPrintList.SelectedIndex = i;
                    break;
                }
            }
        }
    }
}